<template>
  <div class="chat-view">
    <!-- 移动端遮罩 -->
    <div 
      v-if="showSidebar && isMobile" 
      class="mobile-overlay"
      @click="toggleSidebar"
    />

    <!-- 侧边栏 -->
    <div 
      class="sidebar"
      :class="{ 'show': showSidebar }"
    >
      <ChatSidebar
        :list="conversations"
        :current-id="currentConversationId"
        :copy-right="'© 2024 AI助手'"
        @change-current-id="handleConversationChange"
        @new-conversation="handleNewConversation"
      />
    </div>

    <!-- 主聊天区域 -->
    <div class="main-chat">
      <!-- 头部 -->
      <ChatHeader
        :title="currentConversationTitle"
        :is-mobile="isMobile"
        @toggle-sidebar="toggleSidebar"
      />

      <!-- 消息列表 -->
      <div class="messages-container" ref="messagesContainer">
        <div v-if="loading && messages.length === 0" class="loading-container">
          <Loading message="正在加载对话..." />
        </div>
        
        <div v-else-if="messages.length === 0" class="empty-state">
          <div class="empty-icon">
            <svg class="w-16 h-16 text-gray-300" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd" d="M18 10c0 3.866-3.582 7-8 7a8.841 8.841 0 01-4.083-.98L2 17l1.338-3.123C2.493 12.767 2 11.434 2 10c0-3.866 3.582-7 8-7s8 3.134 8 7zM7 9H5v2h2V9zm8 0h-2v2h2V9zM9 9h2v2H9V9z" clip-rule="evenodd" />
            </svg>
          </div>
          <h3 class="empty-title">开始新的对话</h3>
          <p class="empty-description">发送消息开始与AI助手的对话</p>
        </div>

        <div v-else class="messages-list">
          <ChatMessage
            v-for="message in messages"
            :key="message.id"
            :message="message"
            @copy="handleCopyMessage"
            @regenerate="handleRegenerateMessage"
          />
          
          <!-- 正在输入指示器 -->
          <div v-if="isTyping" class="typing-indicator">
            <div class="typing-avatar">
              <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20">
                <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <div class="typing-content">
              <div class="typing-dots">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <ChatInput
        :loading="isTyping"
        :disabled="loading"
        @send="handleSendMessage"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import ChatSidebar from '@/components/chat/ChatSidebar.vue'
import ChatHeader from '@/components/chat/ChatHeader.vue'
import ChatMessage from '@/components/chat/ChatMessage.vue'
import ChatInput from '@/components/chat/ChatInput.vue'
import Loading from '@/components/base/Loading.vue'
import type { ConversationItem, ChatItem } from '@/types/app'

// 响应式状态
const showSidebar = ref(false)
const loading = ref(false)
const isTyping = ref(false)
const currentConversationId = ref<string>('')
const conversations = ref<ConversationItem[]>([])
const messages = ref<ChatItem[]>([])
const messagesContainer = ref<HTMLElement>()

// 计算属性
const isMobile = computed(() => {
  return window.innerWidth < 768
})

const currentConversationTitle = computed(() => {
  const current = conversations.value.find(c => c.id === currentConversationId.value)
  return current?.name || '新对话'
})

// 方法
const toggleSidebar = () => {
  showSidebar.value = !showSidebar.value
}

const handleConversationChange = (conversationId: string) => {
  currentConversationId.value = conversationId
  loadMessages(conversationId)
  if (isMobile.value) {
    showSidebar.value = false
  }
}

const handleNewConversation = () => {
  const newConversation: ConversationItem = {
    id: generateId(),
    name: '新对话'
  }
  conversations.value.unshift(newConversation)
  currentConversationId.value = newConversation.id
  messages.value = []
  if (isMobile.value) {
    showSidebar.value = false
  }
}

const handleSendMessage = async (content: string, files: File[]) => {
  if (!content.trim() && files.length === 0) return

  const userMessage: ChatItem = {
    id: generateId(),
    content,
    isAnswer: false,
    message_files: files.map(file => ({
      id: file.name,
      type: file.type,
      url: URL.createObjectURL(file),
      belongs_to: 'user'
    })),
  }

  messages.value.push(userMessage)
  scrollToBottom()

  // 如果是新对话，更新标题
  if (messages.value.length === 1) {
    updateConversationTitle(currentConversationId.value, content)
  }

  // 模拟AI回复
  isTyping.value = true
  
  try {
    // 这里应该调用实际的AI API
    await simulateAIResponse(content)
  } catch (error) {
    console.error('发送消息失败:', error)
    // 处理错误
  } finally {
    isTyping.value = false
  }
}

const handleCopyMessage = async (content: string) => {
  try {
    await navigator.clipboard.writeText(content)
    // 可以添加成功提示
    console.log('消息已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
  }
}

const handleRegenerateMessage = async (messageId: string) => {
  const messageIndex = messages.value.findIndex(m => m.id === messageId)
  if (messageIndex === -1) return

  // 移除该消息及之后的所有消息
  messages.value = messages.value.slice(0, messageIndex)
  
  // 获取上一条用户消息
  const lastUserMessage = messages.value.filter(m => !m.isAnswer).pop()
  if (lastUserMessage) {
    isTyping.value = true
    try {
      await simulateAIResponse(lastUserMessage.content)
    } catch (error) {
      console.error('重新生成失败:', error)
    } finally {
      isTyping.value = false
    }
  }
}

const loadMessages = async (_conversationId: string) => {
  loading.value = true
  try {
    // 这里应该从API加载消息
    // 暂时使用模拟数据
    messages.value = []
  } catch (error) {
    console.error('加载消息失败:', error)
  } finally {
    loading.value = false
  }
}

const updateConversationTitle = (conversationId: string, firstMessage: string) => {
  const conversation = conversations.value.find(c => c.id === conversationId)
  if (conversation) {
    conversation.name = firstMessage.slice(0, 30) + (firstMessage.length > 30 ? '...' : '')
  }
}

const simulateAIResponse = async (userMessage: string) => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 1000 + Math.random() * 2000))

  const aiMessage: ChatItem = {
    id: generateId(),
    content: `这是对"${userMessage}"的回复。我是AI助手，很高兴为您服务！`,
    isAnswer: true,
    message_files: [],
  }

  messages.value.push(aiMessage)
  scrollToBottom()
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  scrollToBottom()
}, { deep: true })

// 初始化
onMounted(() => {
  // 创建默认对话
  handleNewConversation()
  
  // 在桌面端默认显示侧边栏
  if (!isMobile.value) {
    showSidebar.value = true
  }
})
</script>

<style scoped>
.chat-view {
  @apply flex h-screen bg-gray-100;
}

.mobile-overlay {
  @apply fixed inset-0 bg-black bg-opacity-50 z-40 md:hidden;
}

.sidebar {
  @apply w-80 bg-white border-r border-gray-200 flex-shrink-0 transform -translate-x-full transition-transform duration-300 ease-in-out z-50;
}

.sidebar.show {
  @apply translate-x-0;
}

@media (min-width: 768px) {
  .sidebar {
    @apply relative translate-x-0;
  }
  
  .sidebar.show {
    @apply translate-x-0;
  }
}

.main-chat {
  @apply flex-1 flex flex-col min-w-0;
}

.messages-container {
  @apply flex-1 overflow-y-auto;
}

.loading-container {
  @apply flex items-center justify-center h-full;
}

.empty-state {
  @apply flex flex-col items-center justify-center h-full text-center p-8;
}

.empty-icon {
  @apply mb-4;
}

.empty-title {
  @apply text-xl font-semibold text-gray-700 mb-2;
}

.empty-description {
  @apply text-gray-500;
}

.messages-list {
  @apply divide-y divide-gray-100;
}

.typing-indicator {
  @apply flex gap-3 p-4;
}

.typing-avatar {
  @apply flex-shrink-0 w-8 h-8 rounded-full bg-green-500 text-white flex items-center justify-center;
}

.typing-content {
  @apply flex-1;
}

.typing-dots {
  @apply flex gap-1;
}

.typing-dots span {
  @apply w-2 h-2 bg-gray-400 rounded-full animate-pulse;
  animation-delay: calc(var(--i) * 0.2s);
}

.typing-dots span:nth-child(1) { --i: 0; }
.typing-dots span:nth-child(2) { --i: 1; }
.typing-dots span:nth-child(3) { --i: 2; }
</style> 